package cn.zhihong.service.impl;

import cn.zhihong.common.CustomException;
import cn.zhihong.dto.SetmealDto;
import cn.zhihong.pojo.SetmealDish;
import cn.zhihong.service.SetmealDishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zhihong.pojo.Setmeal;
import cn.zhihong.service.SetmealService;
import cn.zhihong.mapper.SetmealMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 86183
* @description 针对表【setmeal(套餐)】的数据库操作Service实现
* @createDate 2022-04-23 09:49:53
*/
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
    implements SetmealService{
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * @author 庄志宏
     * @date: 2022/4/25 15:42
     * 保存套餐和套餐菜品
     */

    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息，操作setmeal表
        this.save(setmealDto);
        String setmealId = setmealDto.getId().toString();
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> list = setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
            return setmealDish;
        }).collect(Collectors.toList());
        //保存套餐和菜品的关联信息，操作setmeal_dish表
        setmealDishService.saveBatch(list);
    }
    /**
     * @author 庄志宏
     * @date: 2022/4/25 16:24
     * 根据id修改套餐和套餐菜品关联表
     */
    @Transactional
    @Override
    public void updateWithDish(SetmealDto setmealDto) {
        this.updateById(setmealDto);
        Long setmealId = setmealDto.getId();
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,setmealId);
        List<SetmealDish> list = setmealDishService.list(setmealDishLambdaQueryWrapper);
        setmealDishService.updateBatchById(list);
    }

    @Transactional
    @Override
    public void removeWithDish(Long[] ids) {
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        for (Long id: ids){
            Setmeal setmeal = this.getById(id);
            Integer status = setmeal.getStatus();
            String name = setmeal.getName();
            if (status == 1){
                throw new CustomException(name + "套餐在启售中，不能删除");
            }
            this.removeById(id);
            //根据id查询对应的套餐菜品关联表的数据
            setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,id);
            setmealDishService.remove(setmealDishLambdaQueryWrapper);
        }
    }
}




